/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.intercept;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import com.pmc.dwa.security.model.TRole;
import com.pmc.dwa.security.model.TSect;
import com.pmc.dwa.security.service.IUserService;

/**
 * @description 资源源数据定义，将所有的资源和权限对应关系建立起来，即定义某一资源可以被哪些角色访问
 * @author aokunsang
 * @date 2013-1-6
 */
public class PmcSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

	private IUserService userService;
	private static Map<String,Collection<ConfigAttribute>> resourceMap = null;
	private static HashMap<String,Collection<String>> roleGroupidMap = null;
	private AntPathMatcher urlMatcher = new AntPathMatcher();
	
	public PmcSecurityMetadataSource(IUserService userService){
		this.userService = userService;
	}
	
	/* 获取资源文件和角色对应关系，封装到resourceMap里面*/
	public void loadResourcesDefine(){
		if(resourceMap==null){
			resourceMap = new HashMap<String,Collection<ConfigAttribute>>();
		}else{
			resourceMap.clear();
		}
		if(roleGroupidMap==null){
			roleGroupidMap = new HashMap<String, Collection<String>>();
		}else{
			roleGroupidMap.clear();
		}
		List<TRole> roles = userService.findAllRoles();
		if(roles == null) return; //throw new PmcRuntimeException("------------系统中还没有角色，请先添加角色-------");
		for(TRole role : roles){
			String rolename = role.getRolename();   //角色名(全英文)
			List<TSect> sects = userService.findSectByRolename(rolename);
			if(sects==null) continue;
			for(TSect sect : sects){
				if(StringUtils.isEmpty(sect.getSectname())) continue;
				//资源角色Map操作
				Collection<ConfigAttribute> configAttributes = null;
				ConfigAttribute configAttribute = new SecurityConfig(rolename);
				if(resourceMap.containsKey(sect.getSectname())){
					configAttributes = resourceMap.get(sect.getSectname());
					configAttributes.add(configAttribute);
				}else{
					configAttributes = new ArrayList<ConfigAttribute>() ;
					configAttributes.add(configAttribute);
					resourceMap.put(sect.getSectname(), configAttributes);
				}
				//角色和groupId的Map操作（主要用于判断登录用户是否有权限）
				Collection<String> roleList = null;
				if(roleGroupidMap.containsKey(sect.getGroup_id())){
					roleList = roleGroupidMap.get(sect.getGroup_id());
					roleList.add(rolename);
				}else{
					roleList = new HashSet<String>();
					roleList.add(rolename);
					roleGroupidMap.put(sect.getGroup_id(), roleList);
				}
			}
		}
	}
	
	@Override
	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return new ArrayList<ConfigAttribute>();
	}

	/* 根据请求的资源地址，获取它所拥有的权限*/
	@Override
	public Collection<ConfigAttribute> getAttributes(Object obj)
			throws IllegalArgumentException {
		//获取请求的url地址
		String url = ((FilterInvocation)obj).getRequestUrl();
		Iterator<String> iter = resourceMap.keySet().iterator();
		while(iter.hasNext()){
			String _url = iter.next();
			if(_url.indexOf("?")!=-1){
				_url = _url.substring(0, _url.indexOf("?"));
			}
			if(urlMatcher.match(_url,url)){
				return resourceMap.get(_url);
			}
		}
		return null;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}
	/**
	 * 获取资源
	 * @return
	 */
	public static Map<String,Collection<ConfigAttribute>> getAllResources(){
		return resourceMap;
	}
	/**
	 * 获取角色和groupid集合
	 * @return
	 */
	public static Map<String,Collection<String>> getAllRoleGroupid(){
		return roleGroupidMap;
	}
}
